﻿using Furion.DatabaseAccessor;
using Furion.DatabaseAccessor.Extensions;
using Furion.DependencyInjection;
using Furion.DynamicApiController;
using Furion.FriendlyException;
using LimaLims.Application.Service.Base.Dto;
using LimaLims.Application.Service.Basic.Dto;
using LimaLims.Core;
using LimaLims.Core.Entity.Basic;
using Mapster;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
namespace LimaLims.Application.Service.Basic
{
    /// <summary>
    ///班组服务API
    /// </summary>
    [ApiDescriptionSettings(Name = "Team", Order = 156)]
    [Route("api")]
    public class TeamService : ITeamService, IDynamicApiController, ITransient
    {
        private readonly IRepository<Team> _teamRep;  // 产品表仓储

        public TeamService(IRepository<Team> teamRep)
        {
            _teamRep = teamRep;
        }

        /// <summary>
        /// 新增
        /// </summary>
        [HttpPost("team/add")]
        public async Task Add(AddTeamInput input)
        {
            var isExist = await _teamRep.DetachedEntities.AnyAsync(u => u.Name == input.Name && u.WorkName == input.WorkName);
            if (isExist)
                throw Oops.Oh("已存在同一车间下相同班组名称！");

            var team = input.Adapt<Team>();

            await team.InsertAsync();
        }

        [HttpPost("team/delete")]
        public async Task Delete(long id)
        {
            var team = await _teamRep.DetachedEntities.Include(s=>s.SysUsers).Include(s=>s.ExperimentPlans).FirstOrDefaultAsync(u => u.Id == id);
            if (team == null)
                throw Oops.Oh("不存在此数据");

            if (team.SysUsers.Any())
            {
                throw Oops.Oh("当前班组下拥有系统用户，请勿直接删除！");
            }
            if (team.ExperimentPlans.Any())
            {
                throw Oops.Oh("当前班组下拥有试验计划信息，请勿直接删除！");
            }
            await team.DeleteAsync();
        }
        [HttpGet("team/detail")]
        public async Task<Team> Detail(long id)
        {
            var team = await _teamRep.DetachedEntities.FirstOrDefaultAsync(u => u.Id == id);
            if (team == null)
                throw Oops.Oh("不存在此数据");

            return team;
        }
        [HttpPost("team/edit")]
        public async Task Edit(EditTeamInput input)
        {
            var team = await _teamRep.DetachedEntities.FirstOrDefaultAsync(u => u.Id == input.Id);
            if (team == null)
                throw Oops.Oh("不存在此数据！");

            var isExist = await _teamRep.DetachedEntities.AnyAsync(u => u.Name == input.Name && u.WorkName == input.WorkName && u.Id != input.Id);
            if (isExist)
                throw Oops.Oh("已存在同一车间下相同班组名称!");

            var teamModel = input.Adapt<Team>();

            await teamModel.UpdateAsync();
        }

        /// <summary>
        /// 下拉数据
        /// </summary>
        /// <returns></returns>
        [HttpGet("team/selectList")]
        public async Task<List<SelectDto>> SelectList()
        {
            var list = await _teamRep.DetachedEntities.Where(s => s.ValidStatus).OrderBy(s => s.Sort).ToListAsync();
            return list.Select(x => new SelectDto
            {
                Value = x.Id,
                Label = $"{x.WorkName}-{x.Name}"
            }).ToList();
        }

        [HttpGet("team/page")]
        public async Task<PageResult<TeamOutput>> QueryPage([FromQuery] TeamPageInput input)
        {
            var name = !string.IsNullOrEmpty(input.SearchValue?.Trim());
            var code = !string.IsNullOrEmpty(input.WorkName?.Trim());
            var items = await _teamRep.DetachedEntities.Include(s=>s.ExperimentStation)
                                         .Where((name, u => EF.Functions.Like(u.Name, $"%{input.SearchValue.Trim()}%")))
                                         .Where((code, u => EF.Functions.Like(u.WorkName, $"%{input.WorkName.Trim()}%")))
                                         .Where(input.ValidStatus.HasValue, u => u.ValidStatus == input.ValidStatus)
                                         .OrderBy(u => u.Sort)
                                         .Select(u => new TeamOutput
                                         {
                                             Id = u.Id,
                                             Name = u.Name,
                                             WorkName = u.WorkName,
                                             Remark = u.Remark,
                                             ExperimentStationId = u.ExperimentStationId,
                                             ExperimentStationName  =u.ExperimentStation.Name,
                                             ValidStatus = u.ValidStatus,
                                             Sort = u.Sort,
                                             CreatedTime = u.CreatedTime,
                                             CreatedUserName = u.CreatedUserName,
                                             UpdatedTime = u.UpdatedTime,
                                             UpdatedUserName = u.UpdatedUserName
                                         }).ToADPagedListAsync(input.PageNo, input.PageSize);

            return items;
        }
    }
}
